<template>
  <div>
    <el-form ref="userForm" :model="userData" label-width="80px" :rules="rules">
      <el-form-item label="用户名" prop='username'>
        <el-input
          v-model="userData.username"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          placeholder="请输入密码"
          v-model="userData.password"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="userLogin">登录</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //登录携带数据
      userData: {
        username: "admin",
        password: "123456",
      },
      // 表单验证数据
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 12, message: '密码长度为6-12', trigger: 'blur' }
          ],
      },
    };
  },
  methods: {
    // 用户登录
    userLogin() {
        this.$refs['userForm'].validate(val=>{
            if(val){
                this.loginRequest()
            }else{
                this.$message.error('注意提示')  
            }
        })
    },
    //登录请求
    loginRequest(){
        let { username, password } = this.userData;
      this.$req.post("/login", { username, password }).then((res) => {
        let {
          data: { data, meta },
        } = res;
        if (meta.status === 200) {
          this.$message.success(meta.msg);
          this.$store.commit('saveUserInfo',data)
          this.$router.push('/')
        } else if (meta.status !== 200) {
          this.$message.error(meta.msg);
        }
      });
    }
  },
};
</script>

<style>
</style>